package com.xxl.job.core.handler;

import com.autonavi.yunda.yunji.core.engine.script.InterfaceScriptClass;
import com.autonavi.yunda.yunji.core.engine.script.ScriptClassManager;
import com.autonavi.yunda.yunji.core.enums.InterfaceStatus;
import com.autonavi.yunda.yunji.core.service.ITaskConfigService;
import com.autonavi.yunda.yunji.core.vo.EngineInterfaceConfigVO;
import com.xxl.job.core.handler.impl.EngineJobHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author cizhong.wcs
 * @date 2023/7/27 19:16
 * <p>
 * 函数管理脚本管理器
 */
@Slf4j
@Component
public class TaskJobHandlerManager {
    public static Map<String, EngineJobHandler> jobHandlerMap = new ConcurrentHashMap<>();
    @Resource
    private ITaskConfigService taskConfigService;

    public void checkAndRefreshJobHandlerManager() {
        //更新缓存中已有的task
        jobHandlerMap.forEach((key, jobHandler) -> {
            EngineInterfaceConfigVO engineTaskConfigVO = taskConfigService.findEngineTaskConfigVO(key);
            boolean dbCacheNotConsistent = engineTaskConfigVO == null || !engineTaskConfigVO.getUpdateTime().equals(jobHandler.scriptClass.updateTime);
            if (dbCacheNotConsistent) {
                log.info("dbCacheNotConsistent task start need refresh,taskName= {}", key);
                try {
                    refreshFunctionCache(key);
                } catch (Exception e) {
                    log.info("checkAndRefreshScriptClassManager error ,taskName= {}", key, e);
                }
            }
        });
        //更新缓存中没有的函数
        Set<String> existsTask = jobHandlerMap.keySet();
        List<String> newPublishedTasks = taskConfigService.listNewPublishedTasks(existsTask);
        if (!newPublishedTasks.isEmpty()) {
            log.warn("新增 Tasks list = {}", newPublishedTasks);
        }
        newPublishedTasks.forEach(taskName -> {
            try {
                refreshFunctionCache(taskName);
            } catch (Exception e) {
                log.error("checkAndRefreshScriptClassManager error taskName= {}", taskName, e);
            }
        });
    }


    /**
     * 强制刷新函数的缓存
     */
    public void refreshFunctionCache(String taskName) {
        EngineInterfaceConfigVO vo = taskConfigService.findEngineTaskConfigVO(taskName);
        if (vo == null || !vo.getStatus().equals(InterfaceStatus.PUBLISHED)) {
            jobHandlerMap.remove(taskName);
            return;
        }
        InterfaceScriptClass scriptClass = ScriptClassManager.generateInterfaceScriptClass(vo);
        jobHandlerMap.put(taskName, new EngineJobHandler(scriptClass));
    }

}
